package com.cdtye.shuoh.service.device.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cdtye.shuoh.domain.device.entity.DeviceInfo;
import com.cdtye.shuoh.domain.device.vo.DeviceInfoVo;
import com.cdtye.shuoh.mapper.device.DeviceInfoMapper;
import com.cdtye.shuoh.service.device.DeviceInfoService;
import com.cdtye.shuoh.util.text.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DeviceInfoServiceImpl extends ServiceImpl<DeviceInfoMapper, DeviceInfo> implements DeviceInfoService {

    @Autowired
    DeviceInfoMapper deviceInfoMapper;

    public DeviceInfo findOneByNodeId(String nodeId){
        QueryWrapper<DeviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("node_id",nodeId);
        return deviceInfoMapper.selectOne(queryWrapper);
    }

    public int deleteByDeviceId(String deviceId){
        QueryWrapper<DeviceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("device_id",deviceId);
        return deviceInfoMapper.delete(wrapper);
    }

    public int deleteByNodeId(String nodeId){
        QueryWrapper<DeviceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id",nodeId);
        return deviceInfoMapper.delete(wrapper);
    }

    public DeviceInfo findOneByDeviceId(String deviceId){
        QueryWrapper<DeviceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("device_id",deviceId);
        return deviceInfoMapper.selectOne(wrapper);
    }

    public int updateDeviceInfoByNodeId(DeviceInfo deviceInfo){
        UpdateWrapper<DeviceInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("node_id",deviceInfo.getNodeId());
        return deviceInfoMapper.update(deviceInfo,wrapper);
    }

    public int updateDeviceInfo(DeviceInfo deviceInfo){
        return deviceInfoMapper.updateById(deviceInfo);
    }

    public IPage<DeviceInfo> pageList(DeviceInfoVo vo){
        return deviceInfoMapper.pageList(vo.page(),vo);
    }

    public DeviceInfo insertOrUpdateByNodeId(DeviceInfo deviceInfo){
        DeviceInfo old = findOneByNodeId(deviceInfo.getNodeId());
        if(old==null){
            deviceInfo.setDeviceId(UUID.getUUID());
            deviceInfoMapper.insert(deviceInfo);
        }else{
            deviceInfo.setDeviceId(old.getDeviceId());
            updateDeviceInfoByNodeId(deviceInfo);
        }
        return deviceInfo;
    }
}
